package com.team.childapp.ui.setting

import android.content.Intent
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.textservice.TextInfo
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.transition.Visibility
import com.team.childapp.R
import com.team.childapp.base.App
import com.team.childapp.base.activity.BaseActivity
import com.team.childapp.base.listener.ICallBackResultListener
import com.team.childapp.bean.AvatarItem
import com.team.childapp.bean.BaseResponse
import com.team.childapp.bean.MainItem
import com.team.childapp.bean.login.LoginBean
import com.team.childapp.bean.login.UserInfoBean
import com.team.childapp.config.BaseConfig
import com.team.childapp.databinding.ActivitySettingAgeBinding
import com.team.childapp.http.LoginLogical
import com.team.childapp.http.MyInfoLogical
import com.team.childapp.http.base.BaseReqBean
import com.team.childapp.ui.MainActivity
import com.team.childapp.ui.dialog.DatePickerDialogFragment

/**
 * Create on: 2024/12/26
 * by Mr.Zhu
 * Description: 设置信息页面
 */
class SettingInformationActivity : BaseActivity<ActivitySettingAgeBinding>(R.layout.activity_setting_age) {
    private var currentSelect : Int = 1 //当前默认头像选择
    private var currentAvatarCode : String = "" //当前默认头像编码
    private val listItem = arrayListOf<AvatarItem>()
    private var currentSex : Int = 0 //性别 0 是男 1是女
    private var birthday : String= "" //生日
    private lateinit var datePickerDialogFragment: DatePickerDialogFragment
    private var soundPool: SoundPool? = null
    private var soundId: Int = 0
    private val list = arrayListOf<Int>()
    private  var sexFlag=0;
    private  var avatar : String= "" //头像编码
    override fun initData() {
        listItem.add(AvatarItem(0,"avatar001", R.mipmap.boy_1))
        listItem.add(AvatarItem(1,"avatar002", R.mipmap.boy_2))
        listItem.add(AvatarItem(2,"avatar003", R.mipmap.boy_3))
        listItem.add(AvatarItem(3,"avatar004", R.mipmap.girl_1))
        listItem.add(AvatarItem(4,"avatar005", R.mipmap.girl_2,))
        initSounds()
        initUserinfo()
        setSexAndAgeInit()
        setNickAndHeadInit()
    }

    private fun initSounds(){
        sexFlag= App.application().getShareData().getInt(BaseConfig.USER_SEX)

        // 初始化 SoundPool
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()

        soundPool = SoundPool.Builder()
            .setMaxStreams(5)
            .setAudioAttributes(audioAttributes)
            .build()
    }
    private fun initUserinfo(){
        var deviceCode="1111"
        LoginLogical.getInstanceLogin().getDeviceInfo(this,deviceCode,
            object : ICallBackResultListener {
                override fun onCallBack(result: Any?) {
                    println("回调执行了，result: $result") // 打
                    if (result == null) {
                        return
                    }
                    val userInfo: UserInfoBean = result as UserInfoBean? ?: return
                    currentSex = userInfo.sex
                    currentSelect = listItem.find { it.itemCode.equals(userInfo.getAvatar()) }?.itemIndex ?: 0
                    setSex()
                    setSelect()
                    if (!TextUtils.isEmpty(userInfo.birthday)) {
                        mBinding.tvSelectAge.text = userInfo.birthday
                        birthday=userInfo.birthday
                    }
                    if (!TextUtils.isEmpty(userInfo.userName)) {
                        mBinding.etNickName.setText(userInfo.userName)
                    }
                }
            })
    }

    //性别和年龄的设置
    private fun setSexAndAgeInit(){
        setSex()
        mBinding.layoutBoy.setOnClickListener {
            currentSex = 0
            setSex()
            list.clear()
            list.add(R.raw.boy_0)
            playAudio()
        }
        mBinding.layoutGirl.setOnClickListener {
            currentSex = 1
            setSex()
            list.clear()
            list.add(R.raw.girl_1)
            playAudio()
        }

        mBinding.layoutSelectAge.setOnClickListener {

            if (!datePickerDialogFragment.isAdded) {
                if(!birthday.isNullOrEmpty()) {
                    val (year, month, day) = birthday.split("-")
                    // 设置初始值
                    datePickerDialogFragment.setSelectedDate(Integer.parseInt(year),Integer.parseInt(month) ,Integer.parseInt(day));
                }
                datePickerDialogFragment.show(fragmentManager, "DatePickerDialogFragment")
            }
        }

        // 初始化日期选择器对话框
        datePickerDialogFragment = DatePickerDialogFragment().apply {
            setOnDateChooseListener { year, month, day ->
                mBinding.tvSelectAge.text = "$year-$month-$day"
            }
        }

        mBinding.settingImageBack.setOnClickListener {
            finish()
        }
        mBinding.layoutNext.setOnClickListener {
            if (TextUtils.isEmpty(mBinding.tvSelectAge.text.toString())) {
                Toast.makeText(this, "请选择出生日期", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            mBinding.layoutSexAndAge.animate()
                .alpha(0f)
                .setDuration(300)
                .withEndAction{
                    mBinding.layoutSexAndAge.visibility = android.view.View.GONE
                    mBinding.layoutNickAndHeader.visibility = android.view.View.VISIBLE
                    mBinding.layoutNickAndHeader.alpha = 0f
                    mBinding.layoutNickAndHeader.animate()
                        .alpha(1f)
                        .setDuration(300) // 动画持续时间，单位为毫秒
                }
        }
    }

    //设置昵称和头像
    private fun setNickAndHeadInit(){

        setSelect()
        mBinding.layoutHead1.setOnClickListener {
            currentSelect = 0
            setSelect()
        }
        mBinding.layoutHead2.setOnClickListener {
            currentSelect = 1
            setSelect()
        }
        mBinding.layoutHead3.setOnClickListener {
            currentSelect = 2
            setSelect()
        }
        mBinding.layoutHead4.setOnClickListener {
            currentSelect = 3
            setSelect()
        }
        mBinding.layoutHead5.setOnClickListener {
            currentSelect = 4
            setSelect()
        }
        mBinding.settingImageBack2.setOnClickListener {
            mBinding.layoutNickAndHeader.animate()
                .alpha(0f)
                .setDuration(300)
                .withEndAction{
                    mBinding.layoutNickAndHeader.visibility = android.view.View.GONE
                    mBinding.layoutSexAndAge.visibility = android.view.View.VISIBLE
                    mBinding.layoutSexAndAge.alpha = 0f
                    mBinding.layoutSexAndAge.animate()
                        .alpha(1f)
                        .setDuration(300) // 动画持续时间，单位为毫秒
                }
        }
        mBinding.layoutNextFinish.setOnClickListener {
            if (TextUtils.isEmpty(mBinding.etNickName.text.toString())) {
                Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            // TODO: 2024/12/26 调用保存接口，跳转到主页面
//            finish()
            LoginLogical.getInstanceLogin().requestSettingUserName(this, mBinding.etNickName.text.toString(), currentSex,mBinding.tvSelectAge.text.toString(),currentAvatarCode, object :
                ICallBackResultListener {
                override fun onCallBack(result: Any?) {
                    if (result != null) {
                        val userInfo = result as UserInfoBean
                        App.application().getShareData().putInt(BaseConfig.USER_SEX,userInfo.getSex())
//                        Toast.makeText(this@SettingInformationActivity, "保存成功", Toast.LENGTH_SHORT).show()
                        start<MainActivity>()
                        finish()
                    }
                }
            })
        }
    }

    //选择性别
    private fun setSex(){
        when (currentSex) {
            0 -> {
                mBinding.layoutBoy.background = ContextCompat.getDrawable(this,R.drawable.shape_rect_fd6900_radius22)
                mBinding.layoutGirl.background = null
            }
            1 -> {
                mBinding.layoutBoy.background = null
                mBinding.layoutGirl.background = ContextCompat.getDrawable(this,R.drawable.shape_rect_fd6900_radius22)
            }
        }
    }

    //头像设置的
    private fun setSelect(){
        when (currentSelect) {
            0 -> {//第一个
                mBinding.imageviewHead1.setBorderColor(
                    ContextCompat.getColor(this, R.color.color_ce3312)
                )
                mBinding.imageviewHead2.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead3.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead4.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead5.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
            }
            1 -> {//第二个
                mBinding.imageviewHead1.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead2.setBorderColor(
                    ContextCompat.getColor(this, R.color.color_ce3312)
                )
                mBinding.imageviewHead3.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead4.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead5.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
            }
            2 -> {//第三个
                mBinding.imageviewHead1.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead2.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead3.setBorderColor(
                    ContextCompat.getColor(this, R.color.color_ce3312)
                )
                mBinding.imageviewHead4.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead5.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
            }
            3 -> {//第四个
                mBinding.imageviewHead1.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead2.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead3.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead4.setBorderColor(
                    ContextCompat.getColor(this, R.color.color_ce3312)
                )
                mBinding.imageviewHead5.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
            }
            4 -> {//第五个
                mBinding.imageviewHead1.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead2.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead3.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead4.setBorderColor(
                    ContextCompat.getColor(this, R.color.bg_white_66)
                )
                mBinding.imageviewHead5.setBorderColor(
                    ContextCompat.getColor(this, R.color.color_ce3312)
                )
            }
        }
        currentAvatarCode = listItem.find { it.itemIndex==currentSelect}?.itemCode ?: ""
    }
    private fun playAudio() {
        // 加载音频文件，这里假设音频文件在res/raw目录下，名为audio_file.mp3
        soundId = soundPool?.load(this, list.get(0), 1) ?:
                Log.i("soundId", soundId.toString() + "")
        // 设置加载完成监听
        soundPool?.setOnLoadCompleteListener { soundPool, sampleId, status ->
            if (status == 0 && sampleId == soundId) { // 加载成功
                soundPool.play(sampleId, 1.0f, 1.0f, 1, 0, 1.0f) // 播放音频
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放 SoundPool
        soundPool?.release()
        soundPool = null
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_F2) {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            return true
        }
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
           val sexLayVis= mBinding.layoutSexAndAge.visibility
            if(android.view.View.VISIBLE== sexLayVis){
                mBinding.settingImageBack.performClick()

            }else if(android.view.View.GONE== sexLayVis) {
                mBinding.settingImageBack2.performClick()
            }
            return true // 表示事件已处理
        }

        return super.onKeyDown(keyCode, event)
    }
}